package com.tbvtc.agriculturalcreditchainserver2025.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.GroupData;
import com.tbvtc.agriculturalcreditchainserver2025.dto.Cart.UserOrderLimitDot;
import com.tbvtc.agriculturalcreditchainserver2025.dto.CropDto;

import com.tbvtc.agriculturalcreditchainserver2025.dto.farmer.CropSaleDTO;
import com.tbvtc.agriculturalcreditchainserver2025.dto.farmer.registerCropDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.*;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.CropImageMapper;
import com.tbvtc.agriculturalcreditchainserver2025.pojo.*;
import com.tbvtc.agriculturalcreditchainserver2025.service.*;
import com.tbvtc.agriculturalcreditchainserver2025.utils.*;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Pest.PestHttpUtils;
import com.tbvtc.agriculturalcreditchainserver2025.vo.PageVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.PesticideVo.PesticideVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.FindAllCropVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.FoodMessage;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.FoodReportVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@Tag(name = "农户")
@RequestMapping("/farmer")
//@CrossOrigin
public class FarmerController {

    @Autowired
    private FarmerSerive farmerSerive;
    @Autowired
    private PreciseChinaClimateService chinaClimateService;
    @Resource
    private ICropService cropService;
    @Resource
    private IUserService userService;
    @Resource
    private CartService cartService;
    @Resource
    private ITestService testService;
    @Resource
    private IFarmlandInfoService farmlandInfoService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ICropPesticideInfoService cropPesticideInfoService;

    /**
     * 添加农作物阶段信息
     *
     * @param cropDto
     * @return
     * @throws Exception
     */
    @Operation(summary = "添加农作物阶段信息")
    @PostMapping("/addReport")
    public Result addReport(@RequestBody CropDto cropDto) throws Exception {
        TransactionResponse response = farmerSerive.addReport(cropDto);
        return RUtils.success(response);
    }

    /**
     * 获取农作物阶段信息
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Operation(summary = "获取农作物阶段信息")
    @PostMapping("/getReport")
    @Parameters({
            @Parameter(name = "userId", description = "农产品ID")
    })
    public Result getReport(Integer userId) throws Exception {
        Crop crop = cropService.getById(userId);
        List<FoodReportVo> list = farmerSerive.getReport(crop.getName());
        return RUtils.success(list);
    }

    /**
     * 初始化土地
     *
     * @param landInit
     * @return
     * @throws Exception
     */

    @Operation(summary = "初始化土地")
    @PostMapping("/initLand")
    public Result initLand(@RequestBody landInit landInit) throws Exception {
        TransactionResponse response = farmerSerive.initLand(landInit);
        return RUtils.success(response);
    }

    /**
     * 根据id查询土地信息
     *
     * @param id
     * @return
     */
    @Operation(summary = "获取土地信息")
    @PostMapping("/getLandInfo")
    @Parameter(name = "id", description = "土地id")
    public Result getLandInfo(String id) {
        landInit infoById = farmerSerive.getLandInfoById(id);
        //  LandInfo landInfo = new LandInfo(list);
        return RUtils.success(infoById);
    }

    /**
     * 注册农产品
     *
     * @param registerCropDto
     * @return
     * @throws Exception
     */
    @Operation(summary = "注册农产品")
    @PostMapping("/registerCrop")

    public Result registerCrop(@RequestBody registerCropDto registerCropDto) throws Exception {
        TransactionResponse response = farmerSerive.registerCrop(registerCropDto);
        return RUtils.success(response);
    }

    /**
     * 添加物联网设备
     *
     * @return
     * @throws Exception
     */
    @Operation(summary = "添加物联网设备")
    @PostMapping("/addIot")
    public Result addIot(@RequestBody IotInfo iotInfo) throws Exception {
        TransactionResponse response = farmerSerive.addIot(iotInfo);
        return RUtils.success(response);
    }

    /**
     * 查询物联网设备
     *
     * @param deviceId
     * @return
     * @throws Exception
     */
    @Operation(summary = "查询物联网设备")
    @PostMapping("/getIot")
    @Parameter(name = "deviceId", description = "设备ID")
    public Result getIot(String deviceId) throws Exception {
        List list = farmerSerive.getIot(deviceId);
        return RUtils.success(list);

    }

    /**
     * 更新物联网设备
     *
     * @param updateIotInfo
     * @return
     * @throws Exception
     */
    @Operation(summary = "更新物联网设备")
    @PostMapping("/updateIot")
    public Result updateIot(@RequestBody updateIotInfo updateIotInfo) throws Exception {
        TransactionResponse response = farmerSerive.updateIot(updateIotInfo);
        return RUtils.success(response);
    }

    /**
     * 标记农作物已经收获
     *
     * @param foodName
     * @return
     * @throws Exception
     */

    @Operation(summary = "标记农作物已经收获")
    @PostMapping("/markHarvested")
    @Parameter(name = "foodName", description = "农产品名称")
    public Result markHarvested(String foodName) throws Exception {
        TransactionResponse response = farmerSerive.markHarvested(foodName);
        return RUtils.success(response);
    }

    /**
     * 根据userId查询农作物信息
     *
     * @param userId
     * @return
     */
    @Operation(summary = "根据农户id查询农作物信息")
    @PostMapping("/selectFoodByUserId")
    @Parameter(name = "userId", description = "农户id")
    public Result selectFoodByPhone(String userId) {
        User user = userService.getById(userId);
        List<Crop> list = cropService.list(new LambdaQueryWrapper<Crop>()
                .eq(Crop::getPhone, user.getPhone())
        );
        return getResult(list);
    }

    /**
     * 查询全部农作物
     *
     * @return
     */
    @Operation(summary = "查询全部农作物")
    @PostMapping("findAllCrop")
    public Result findAllCrop() {
        List<Crop> list = cropService.list();
        return getResult(list);
    }

    @NotNull
    private Result getResult(List<Crop> list) {
        List<FindAllCropVo> findAllCropVos = BeanUtil.copyToList(list, FindAllCropVo.class);
        Map<String, Integer> collect = farmlandInfoService.list(new LambdaQueryWrapper<FarmlandInfo>()
                .select(FarmlandInfo::getId, FarmlandInfo::getLandName)
        ).stream().collect(Collectors.toMap(FarmlandInfo::getLandName, FarmlandInfo::getId));
        findAllCropVos.forEach(findAllCropVo -> {
            Integer landId = collect.get(findAllCropVo.getLandName());
            String growthStage = stringRedisTemplate.opsForValue().get(RedisConstant.CROP_STAGE_TYPE + findAllCropVo.getName());
            if (growthStage != null) {
                findAllCropVo.setGrowthStage(growthStage);
            } else {
                findAllCropVo.setGrowthStage("尚未添加生长阶段");
            }
            findAllCropVo.setLandId(landId);
        });
        return RUtils.success(findAllCropVos);
    }

    /**
     * 查询全部土地信息
     *
     * @param id
     * @return
     */
    @Operation(summary = "查询农户所有的土地信息")
    @PostMapping("/findAllLand")
    @Parameter(name = "id", description = "用户id")
    public Result findAllLand(Integer id) {
        List land = farmerSerive.findAllLand(id);
        return RUtils.success(land);
    }

    /**
     * 为预约的用户打折
     *
     * @param discount
     * @param price
     * @return
     */

    @Operation(summary = "为预约的用户打折")
    @PostMapping("/discount")
    @Parameters({
            @Parameter(name = "discount", description = "打几折"),
            @Parameter(name = "price", description = "价格")
    })
    public Result discount(Double discount, Double price) {
        Double discount1 = farmerSerive.discount(discount, price);
        return RUtils.success(discount1);
    }


    /**
     * 根据名字查询农作物详情
     *
     * @param foodName
     * @return
     */
    @Operation(summary = "根据CropId查询农作物详情")
    @PostMapping("/findFoodById")
    public Result findFoodByName(Integer CropId) {
        return RUtils.success(farmerSerive.findFoodById(CropId));
    }

    /**
     * 标记土地启用
     *
     * @param landId
     * @param isActive
     * @return
     */
    @Operation(summary = "标记土地启用")
    @PostMapping("/markLandUsed")
    @Parameters({
            @Parameter(name = "landId", description = "土地id"),
            @Parameter(name = "isActive", description = "1启用，2弃用，3闲置")
    })

    public Result markLandUsed(String landId, String isActive) {
        farmerSerive.markLandUsed(landId, isActive);
        return RUtils.success();
    }


    /**
     * 根据经纬度获取气候类
     *
     * @param latitude
     * @param longitude
     * @return
     */
    @PostMapping("/getClimateType")
    @Operation(summary = "根据经纬度获取气候类型")
    public Result getClimateType(double latitude, double longitude) {
        System.out.println(chinaClimateService.getClimateType(latitude, longitude));
        return RUtils.success(chinaClimateService.getClimateType(latitude, longitude));
    }

    /**
     * 根据cropId上架或下架商品
     *
     * @param
     * @return
     */
    @Operation(summary = "批量上架或下架商品")
    @PostMapping("/saleCrop")
    public Result batchSaleCrop(
            @RequestBody CropSaleDTO dto
    ) {
        // 构造更新条件：ID在指定列表中，更新isSale字段
        LambdaUpdateWrapper<Crop> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Crop::getId, dto.getCropIds())  // 条件：ID在cropIds中
                .set(Crop::getIsSale, dto.getIsSale());  // 更新字段：isSale
        // 执行批量更新
        cropService.update(updateWrapper);
        log.info("批量更新完成");
        return RUtils.success();
    }

    /**
     * 农户查看谁购买的物品
     *
     * @param userOrderLimitDot
     * @return
     */
    @Operation(summary = "农户查看物流状态")
    @PostMapping("/findOrderById")
    public Result findOrderById(@RequestBody UserOrderLimitDot userOrderLimitDot) {
//        ResultPage<GroupData> orderById = cartService.findOrderById(userOrderLimitDot);
        IPage<GroupData> orderByIdPage = testService.findOrderByIdPage(userOrderLimitDot);
        PageVo<GroupData> groupDataPageVo = new PageVo<>();
        groupDataPageVo.setTotal(orderByIdPage.getTotal());
        groupDataPageVo.setRecords(orderByIdPage.getRecords());
        return RUtils.success(groupDataPageVo);
    }

    @Operation(summary = "确认发货")
    @PostMapping("/confirmDelivery")
    @Parameters({
            @Parameter(name = "orderId", description = "订单号"),
            @Parameter(name = "expressId", description = "快递单号"),
            @Parameter(name = "expressCompany", description = "快递公司")
    })
    public Result confirmDelivery(String orderId, String expressId, String expressCompany) {
        if (orderId == null) {
            return RUtils.Err(0, "订单号不能为空");
        }
        cartService.confirmDelivery(orderId, expressId, expressCompany);
        return RUtils.success();
    }

    @Operation(summary = "根据cropId获取农药信息")
    @PostMapping("/getPesticideInfo")
    public Result getPesticideInfo(Integer cropId) {
        Crop crop = cropService.getById(cropId);
        List<CropPesticideInfo> list = cropPesticideInfoService.list(new LambdaQueryWrapper<CropPesticideInfo>()
                .eq(CropPesticideInfo::getCropName, crop.getName())
                .select(CropPesticideInfo::getPesticideGenericName)
        );
        List<String> pesticideList = list.stream().map(CropPesticideInfo::getPesticideGenericName).collect(Collectors.toList());
        List<String> fertilizerList = List.of("氮肥", "磷肥", "钾肥", "有机肥", "氮磷钾复合肥", "基肥", "追肥", "叶面肥");
        return RUtils.success(new PesticideVo(pesticideList, fertilizerList));
    }


}
